import { ApiRes, ArticleDetail, Comment, CommentRes } from '@/types/data'
import request from '@/utils/request'
import { RootThunkAction } from '@/types/store'

export function getArticleDetail(id: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiRes<ArticleDetail>>(`/articles/${id}`)

    dispatch({
      type: 'article/set_article_detail',
      payload: res.data.data
    })
  }
}

// 获取文章的评论
export function getCommentList(id: string, offset?: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiRes<CommentRes>>('/comments', {
      params: {
        type: 'a',
        source: id,
        offset
      }
    })

    dispatch({
      type: 'article/set_comment',
      payload: res.data.data
    })
  }
}

// 文章点赞或取消
export function likeArticle(id: string, attitude: number): RootThunkAction {
  return async (dispatch) => {
    if (attitude === 1) {
      // 取消
      await request.delete(`/article/likings/${id}`)
    } else {
      // 点赞
      await request.post('/article/likings', { target: id })
    }

    // 重新获取文章详情
    await dispatch(getArticleDetail(id))
  }
}

// 文章收藏或取消
export function collectArticle(
  id: string,
  is_collected: boolean
): RootThunkAction {
  return async (dispatch) => {
    if (is_collected) {
      // 取消
      await request.delete(`/article/collections/${id}`)
    } else {
      // 收藏
      await request.post('/article/collections', { target: id })
    }

    // 重新获取文章详情
    await dispatch(getArticleDetail(id))
  }
}

// 关注文章作者或取消
export function followUser(
  userId: string,
  is_follow: boolean
): RootThunkAction {
  return async (dispatch, getState) => {
    if (is_follow) {
      // 取消
      await request.delete(`/user/followings/${userId}`)
    } else {
      // 关注
      await request.post('/user/followings', { target: userId })
    }

    await dispatch(getArticleDetail(getState().article.info.art_id))
  }
}

// 发表评论
export function addComment(
  articleId: string,
  content: string
): RootThunkAction {
  return async (dispatch, getState) => {
    const res = await request.post<ApiRes<{ new_obj: Comment }>>('/comments', {
      target: articleId,
      content
    })

    dispatch({
      type: 'article/save_new_comment',
      payload: res.data.data.new_obj
    })
  }
}

// 回复列表
export function getReplyList(id: string, offset: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiRes<CommentRes>>('/comments', {
      params: {
        type: 'c',
        source: id,
        offset
      }
    })

    dispatch({
      type: 'article/save_reply',
      payload: res.data.data
    })
  }
}
